package com.qqtech.qquan.pub.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.qqtech.core.common.annotation.VisitAnnt;
import com.qqtech.core.common.enums.RespEnum;
import com.qqtech.core.common.enums.YesNoEnum;
import com.qqtech.core.common.util.StringUtil;
import com.qqtech.core.common.util.TimeUtil;
import com.qqtech.core.frame.model.PageKit;
import com.qqtech.core.frame.model.PageOrder;
import com.qqtech.core.frame.model.Result;
import com.qqtech.core.frame.service.BaseService;
import com.qqtech.qquan.hi.service.HiOrderService;
import com.qqtech.qquan.homemaking.model.HomemakingOrderVo;
import com.qqtech.qquan.homemaking.service.HomemakingOrderService;
import com.qqtech.qquan.mall.enums.MallConst;
import com.qqtech.qquan.mall.model.MallProductSpec;
import com.qqtech.qquan.mall.service.MallProductSpecService;
import com.qqtech.qquan.order.enums.OrderBaseOrderStatusDictEnum;
import com.qqtech.qquan.order.enums.OrderBaseOrderTypeDictEnum;
import com.qqtech.qquan.order.model.OrderBase;
import com.qqtech.qquan.order.model.OrderBaseQuery;
import com.qqtech.qquan.order.model.OrderBaseVo;
import com.qqtech.qquan.order.model.OrderItemQuery;
import com.qqtech.qquan.order.model.OrderItemVo;
import com.qqtech.qquan.order.service.OrderBaseService;
import com.qqtech.qquan.order.service.OrderItemService;
import com.qqtech.qquan.pub.enums.PubFeedbackLevelDictEnum;
import com.qqtech.qquan.pub.enums.PubFeedbackObjDictEnum;
import com.qqtech.qquan.pub.enums.PubFeedbackScoreDictEnum;
import com.qqtech.qquan.pub.model.PubFeedback;
import com.qqtech.qquan.pub.model.PubFeedbackQuery;
import com.qqtech.qquan.pub.model.PubFeedbackVo;
import com.qqtech.qquan.pub.service.PubFeedbackService;
import com.qqtech.qquan.sys.enums.SysConst;
import com.qqtech.qquan.user.model.UserBaseVo;
import com.qqtech.qquan.user.service.UserBaseService;
import com.qqtech.web.context.BaseWebController;

@Controller
@RequestMapping(value = "/pub/feedback")
public class PubFeedbackController extends BaseWebController<PubFeedback, PubFeedbackQuery> {
	@Resource
	private PubFeedbackService pubFeedbackService;
	
	@Resource
	private OrderItemService orderItemService;
	
	@Resource
	private OrderBaseService orderBaseService;
	
	@Resource
	private UserBaseService userBaseService;
	
	@Resource
	private HomemakingOrderService homemakingOrderService;
	@Resource
	private MallProductSpecService mallProductSpecService;
	@Resource
	private HiOrderService hiOrderService;
    
	@Override
	protected BaseService<PubFeedback> getBaseService() {
		return pubFeedbackService;
	}
	
	/**
	 * 评价列表
	 * 
	 * @param orderBaseQuery
	 * @return
	 */
	@RequestMapping(value = "/page")
	@ResponseBody
	public Result page(@RequestBody PubFeedbackQuery pubFeedbackQuery) {
		Result result = new Result();
		if (pubFeedbackQuery == null) {
			result.addErr("参数不能为空");
		}else {
			if (pubFeedbackQuery.getProductId() == null || pubFeedbackQuery.getType() == null) {
				result.addErr("商品数据错误");
			}
		}
		if (result.checkForm()) {
			pubFeedbackQuery.setStatus(YesNoEnum.YES.getCode());
			Pageable pageKit = new PageKit(pubFeedbackQuery.getPage(), 20, new PageOrder(Direction.DESC, "newAt"));
			Page<PubFeedbackVo> page = pubFeedbackService.queryPageList(pubFeedbackQuery, pageKit);
			List<PubFeedbackVo> feedbackList = page.getContent();
			if(feedbackList != null && feedbackList.size() > 0){
				for(PubFeedbackVo pubFeedbackVo : feedbackList){
		 			UserBaseVo userVo = userBaseService.getById(pubFeedbackVo.getCreatorId());
		 			pubFeedbackVo.setCreatorImg( userVo.getLogo());
		 			pubFeedbackVo.setCreatorName(userVo.getNick());
		 			pubFeedbackVo.setImgString(pubFeedbackVo.getImg(),SysConst.IMG_POSTFIX);
				}
			}
			result.put("page", page);
			result.put("totalPages", page.getTotalPages());
		}
		return result;
	}
	
	/**
	 * 添加商品评价页面入口
	 */
	@VisitAnnt(type = RespEnum.LOGIN)
	@RequestMapping(value = "/toAdd")
	@ResponseBody
	public Result toAdd(@RequestBody OrderBaseQuery orderBaseQuery) {
		Result result = new Result();
		if (orderBaseQuery == null || StringUtil.isBlank(orderBaseQuery.getOrderNo())) {
			result.addErr("参数不能为空");
		}
		if (result.checkForm()) {
			OrderBase order = orderBaseService.getByOrderNo(orderBaseQuery.getOrderNo());
			if (OrderBaseOrderTypeDictEnum.HOMEMAKING.getCode() == order.getOrderType()) {
				HomemakingOrderVo homemakingOrder = homemakingOrderService.getByOrderNo(order.getOrderNo());
				//家政服务的评价，取订单
				List<Map<String,Object>> itemList = new ArrayList<Map<String,Object>>();
				Map<String,Object> map = new HashMap<String, Object>();
				if(StringUtil.isNotBlank(order.getImg())){
					order.setImgString(order.getImg(), MallConst.IMG_SMALL);
				}
				map.put("img", order.getImg());
				map.put("imgItems", order.getImgItems());
				map.put("name", order.getTitle());
				map.put("price", order.getTotal());
				map.put("quntity", 0);
				map.put("orderNo", order.getOrderNo());
				map.put("productId", homemakingOrder.getBaseId());
				map.put("index", 0);
				map.put("fileDomain", order.getFileDomain());
				map.put("orderType", order.getOrderType());
				itemList.add(map);
				result.put("itemList", itemList);
			} else {
				//未评论的订单明细
				OrderItemQuery orderItemQuery = new OrderItemQuery();
				orderItemQuery.setOrderNo(orderBaseQuery.getOrderNo());
				orderItemQuery.setIsComment(YesNoEnum.NO.getCode());
				Pageable pageKit = new PageKit(orderBaseQuery.getPage(), new PageOrder(Direction.DESC, "id"));
				Page<OrderItemVo> page = orderItemService.queryPageList(orderItemQuery, pageKit);
				List<OrderItemVo> itemList = page.getContent();
				if(itemList != null && itemList.size() > 0){
					for(int i = 0; i < itemList.size(); i++){
						OrderItemVo vo = itemList.get(i);
						if(StringUtil.isNotBlank(vo.getImg())){
							vo.setImgString(vo.getImg(), MallConst.IMG_SMALL);
						}
						vo.setIndex(i);
					}
				}
				result.put("itemList", itemList);
			}
		}
		return result;
	}
	
	/**
	 * 添加商品评价
	 */
	@VisitAnnt(type = RespEnum.LOGIN)
	@RequestMapping(value = "/doAdd")
	@ResponseBody
	public Result doAdd(@RequestBody PubFeedback pubFeedback) {
		Result result = new Result();
		if (pubFeedback == null || StringUtil.isBlank(pubFeedback.getOrderNo()) || pubFeedback.getProductId() == null ) {
			result.addErr("参数不能为空");
			return result;
		}
		if (pubFeedback.getType() == null  ) {
			result.addErr("评论业务类型为空");
			return result;
		}
		if(pubFeedback.getScore() == null || StringUtil.isBlank(pubFeedback.getContent())){
			result.addErr("评价内容不能为空");
			return result;
		}
		OrderBase order = orderBaseService.getByOrderNo(pubFeedback.getOrderNo());
		if(order == null || !super.getUserId().equals(order.getBuyerId())){
			result.addErr("评价参数错误");
			return result;
		}
		if (super.getUserId().intValue() != order.getBuyerId().intValue()){
			result.addErr("无权限添加评价");
			return result;
		}
		if(order.getOrderStatus() != null && order.getOrderStatus().intValue() != OrderBaseOrderStatusDictEnum.COMPLETED.getCode()){
			result.addErr("订单未完成");
			return result;
		}
		if(pubFeedback.getScore() > PubFeedbackScoreDictEnum.SCORE5.getCode() ||  pubFeedback.getScore() < PubFeedbackScoreDictEnum.SCORE1.getCode()){
			result.addErr("评分参数错误");
			return result;
		}
		
		//评分对应的等级
		if(pubFeedback.getScore() == PubFeedbackScoreDictEnum.SCORE1.getCode()){
			pubFeedback.setLevel(PubFeedbackLevelDictEnum.BAD.getCode());
		}else if(pubFeedback.getScore() == PubFeedbackScoreDictEnum.SCORE2.getCode()){
			pubFeedback.setLevel(PubFeedbackLevelDictEnum.GENERAL.getCode());
		}else if(pubFeedback.getScore() >= PubFeedbackScoreDictEnum.SCORE3.getCode()){
			pubFeedback.setLevel(PubFeedbackLevelDictEnum.GOOD.getCode());
		}
		if (OrderBaseOrderTypeDictEnum.HOMEMAKING.getCode() == order.getOrderType()) {
			pubFeedback.setShopId(0);
		} else {
			pubFeedback.setShopId(order.getShopId());
		}
		pubFeedback.setAnonymous(YesNoEnum.YES.getCode());
		pubFeedback.setStatus(YesNoEnum.YES.getCode());
		pubFeedback.setCreatorId(super.getUserId());
		pubFeedback.setNewAt(TimeUtil.now());
		pubFeedback.setUpdAt(TimeUtil.now());
		pubFeedbackService.handleSaveFeedback(pubFeedback);
	
		return result;
	}
	
	
	/**
	 * 添加商品评价
	 */
	@VisitAnnt(type = RespEnum.LOGIN)
	@RequestMapping(value = "/doAdd2")
	@ResponseBody
	public Result doAdd2(@RequestBody OrderBaseVo orderBaseVo) {
		Result result = new Result();
		OrderBase order = orderBaseService.getByOrderNo(orderBaseVo.getOrderNo());
		if(order == null || !super.getUserId().equals(order.getBuyerId())){
			result.addErr("评价参数错误");
			return result;
		}
		if (super.getUserId().intValue() != order.getBuyerId().intValue()){
			result.addErr("无权限添加评价");
			return result;
		}
		if(order.getOrderStatus() != null && order.getOrderStatus().intValue() != OrderBaseOrderStatusDictEnum.COMPLETED.getCode()){
			result.addErr("订单未完成");
			return result;
		}
		
		List<PubFeedback> addList = orderBaseVo.getFeedbackList();
		if (addList == null){
			result.addErr("评价信息不存在");
			return result;
		}
		
		for(PubFeedback pubFeedback : addList){
			//评分对应的等级
			if(pubFeedback.getScore() == PubFeedbackScoreDictEnum.SCORE1.getCode()){
				pubFeedback.setLevel(PubFeedbackLevelDictEnum.BAD.getCode());
			}else if(pubFeedback.getScore() == PubFeedbackScoreDictEnum.SCORE2.getCode()){
				pubFeedback.setLevel(PubFeedbackLevelDictEnum.GENERAL.getCode());
			}else if(pubFeedback.getScore() >= PubFeedbackScoreDictEnum.SCORE3.getCode()){
				pubFeedback.setLevel(PubFeedbackLevelDictEnum.GOOD.getCode());
			}
			if (OrderBaseOrderTypeDictEnum.HOMEMAKING.getCode() == order.getOrderType().intValue()) {
				pubFeedback.setShopId(0);
				pubFeedback.setObj(null);
			} else {
				MallProductSpec spec = mallProductSpecService.getById(pubFeedback.getProductId());
				pubFeedback.setProductId(spec.getProductId());
				pubFeedback.setShopId(order.getShopId());
				pubFeedback.setObj(PubFeedbackObjDictEnum.PRODUCT.getCode());
			}
			pubFeedback.setType(order.getOrderType());
			pubFeedback.setAnonymous(YesNoEnum.YES.getCode());
			pubFeedback.setStatus(YesNoEnum.YES.getCode());
			pubFeedback.setCreatorId(super.getUserId());
			pubFeedback.setNewAt(TimeUtil.now());
			pubFeedback.setUpdAt(TimeUtil.now());
		}
		
		//评价物流
		if(OrderBaseOrderTypeDictEnum.QUANMALL.getCode() == order.getOrderType().intValue()){
			PubFeedback delivery = new PubFeedback();
			delivery.setObj(PubFeedbackObjDictEnum.DELIVERY.getCode());
			delivery.setScore(orderBaseVo.getDeliveryScore());
			delivery.setLevel(PubFeedbackLevelDictEnum.GOOD.getCode());
			if(StringUtil.isNotBlank(orderBaseVo.getDeliveryContent())){
				delivery.setContent(orderBaseVo.getDeliveryContent());
			}else{
				delivery.setContent("");
			}
			delivery.setImg("");
			delivery.setOrderNo(order.getOrderNo());
			delivery.setProductId(0);
			delivery.setShopId(0);
			delivery.setType(order.getOrderType());
			delivery.setAnonymous(YesNoEnum.YES.getCode());
			delivery.setStatus(YesNoEnum.YES.getCode());
			delivery.setCreatorId(super.getUserId());
			delivery.setNewAt(TimeUtil.now());
			delivery.setUpdAt(TimeUtil.now());
			addList.add(delivery);
		}
		
		pubFeedbackService.handleSaveFeedbackList(addList);
		//荣誉系统，首次评价订单（商城、圈商）  +15荣誉值 +50圈币
		if(order.getOrderType().intValue() == OrderBaseOrderTypeDictEnum.QUANMALL.getCode()
				|| order.getOrderType().intValue() == OrderBaseOrderTypeDictEnum.QSHOP.getCode()){
			hiOrderService.orderComment(super.getUserId(), order.getId());
		}
		return result;
	}
	
}
